package com.awspaas.user.apps.processforsap.util;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.AbstFileProcessor;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.FileProcessorListener;
import com.actionsoft.bpms.util.UtilFile;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.cc.RDSAPI;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.remoting.util.StringUtils;
import com.alipay.sofa.common.profile.StringUtil;
import com.awspaas.user.apps.processforsap.model.DYBG;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class dybgDataExcelImpl extends AbstFileProcessor implements FileProcessorListener {

    private static final String EXTENSION_XLS = ".xls";
    private static final String EXTENSION_XLSX = ".xlsx";

    @Override
    public void uploadBeforeEncrypt(Map<String, Object> param) {
        super.uploadBeforeEncrypt(param);
    }

    @Override
    public void uploadSuccess(Map<String, Object> param) {
        //文件存储
        DCContext context = (DCContext) param.get("DCContext");
        //上传人
        UserContext uc = context.getSession();
        UtilFile tmpFile = new UtilFile(context.getFilePath());

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(context.getFilePath());
//            inputStream = resource.getInputStream();
            //得到Excel工作簿对象
            Workbook wb = null;
            int available = inputStream.available();
            if (available >= 2000000) {//大于2m的文件给与提示
                context.getDCMessage().setMessage("文件过大会读取异常，请传入小于2m大小的文件或者尝试清除没有数据的单元格样式！！！");
                return;
            }
            if (context.getFilePath().endsWith(EXTENSION_XLS)) {
                wb = new HSSFWorkbook(inputStream);
            } else if (context.getFilePath().endsWith(EXTENSION_XLSX)) {
                wb = new XSSFWorkbook(inputStream);
            }

            if (wb == null) {
                context.getDCMessage().setMessage("读取文件错误");
                return;
            }
            createData(context, wb, uc);

            // 创建数据（包含图片）
            context.getDCMessage().setMessage("导入成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            context.getDCMessage().setMessage(ex.getMessage());
        } finally {
            // 删除
            if (tmpFile != null && tmpFile.length() > 0) {
                tmpFile.delete();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception var23) {
                }
            }
        }
    }

    /**
     * 导入数据
     *
     * @param context dc上下文
     * @param wb      上传的excel附件
     * @param uc      用户上下文
     */
    private void createData(DCContext context, Workbook wb, UserContext uc) {
        String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
        RDSAPI rdsapi = SDK.getCCAPI().getRDSAPI(rdsId);
        //默认参数
        String extParam = context.getExtParam();
        if (StringUtils.isBlank(extParam)) {
            context.getDCMessage().setMessage("读取参数失败，导入失败");
            return;
        }
        //扩展参数
        JSONObject params = JSON.parseObject(extParam);
        //流程实例ID
        String processInstId = params.getString("processInstId");
        //子表表名
        String gridTable = params.getString("gridTable");
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 同步读取会自动finish
        // 用于存储从第三行开始的数据
        List<DYBG> dataList = new ArrayList<>();

        // 使用一个 final 数组来包装第一行第二列的数据
        final String[] firstRowSecondColumn = new String[1];

        // 读取 Excel 文件
        EasyExcel.read(context.getFilePath(), DYBG.class, new AnalysisEventListener<DYBG>() {
            @Override
            public void invoke(DYBG data, AnalysisContext context) {
                // 获取第一行第二列的数据
                if (context.readRowHolder().getRowIndex() == 1) {
                    firstRowSecondColumn[0] = data.getZLSJBG();
                }

                // 从第三行开始读取数据
                if (context.readRowHolder().getRowIndex() >= 4) {
                    dataList.add(data);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 读取完成后的操作
                System.out.println("Excel 文件读取完成");
            }
        }).sheet().doRead();
        String plant= firstRowSecondColumn[0];
        if (StringUtil.isEmpty(plant)){
            context.getDCMessage().setMessage("未读取到工厂值，导入失败");
            return;
        }

//        List<Object> list = EasyExcel.read(context.getFilePath()).head(DYBG.class).headRowNumber(2).sheet(0).doReadSync();
        List<BO> boList = new ArrayList<>();
        for (Object data : dataList) {
            // 开始创建子表数据  先获取物料相关信息
            BO gridBo = new BO();
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data));
            for (String key : jsonObject.keySet()) {
                if ("ANLN1".equals(key.toUpperCase())) {
                    String sql = "select * from SAP_ASSET_BASIC where BUKRS = '"+plant+"' and ANLN1 = '"+jsonObject.get(key)+"'";
                    RowMap rowMap = rdsapi.getMap(sql);
                    gridBo.set("ANLKL",rowMap.getString("ANLKL"));
                    gridBo.set("PM",rowMap.getString("TXT50"));
                    gridBo.set("ANLN1",rowMap.getString("ANLN1"));
                    gridBo.set("ZXH",rowMap.getString("ZXH"));
                    gridBo.set("ZGG",rowMap.getString("ZGG"));
                    gridBo.set("WERKS",rowMap.getString("WERKS"));
                    gridBo.set("CFDD",rowMap.getString("STORT"));
                    gridBo.set("ZDYKSSJ",rowMap.getString("ZDYKSSJ"));
                    gridBo.set("ZDYJSSJ",rowMap.getString("ZDYJSSJ"));
                    gridBo.set("ZTZWH",rowMap.getString("ZTZWH"));
                    gridBo.set("KOSTL",rowMap.getString("KOSTL"));
                    gridBo.set("TXT50",rowMap.getString("TXT50"));
                    gridBo.set("ZZLXX",rowMap.getString("ZZLXX"));
                    gridBo.set("ZZLKSSJ",rowMap.getString("ZZLKSSJ"));
                    gridBo.set("ZZLJSSJ",rowMap.getString("ZZLJSSJ"));
                    gridBo.set("ZDYJSSJ",rowMap.getString("DYJSSJ"));
                    gridBo.set("DYJSSJ",rowMap.getString("ZDYJSSJ"));
                    gridBo.set("ZJTH",rowMap.getString("ZJTH"));
                    gridBo.set("SERNR",rowMap.getString("SERNR"));
                    gridBo.set("ZRYRZ",rowMap.getString("ZRZDY"));
                } else {
                    gridBo.set(key.toUpperCase(), jsonObject.get(key));
                }
            }
            boList.add(gridBo);
        }
        BO mainBo = SDK.getBOAPI().query("BO_EU_SAP_FIZCCHANGE").bindId(processInstId).detail();
        mainBo.set("BUKRS",plant);
        SDK.getBOAPI().update("BO_EU_SAP_FIZCCHANGE",mainBo);
        SDK.getBOAPI().create(gridTable, boList, processInstId, uc.getUID());
    }
}